#!/bin/sh

ILIAD=/Volumes/iLiad
TEMP_DIR=/tmp/nytimes-mobile
GROWLNOTIFY=/usr/local/bin/growlnotify
WGET=/usr/local/bin/wget

# notify start of operations
$GROWLNOTIFY -m "Downloading The New York Times (mobile edition)";

# create a temporary working directory, move into it
mkdir $TEMP_DIR; 
cd $TEMP_DIR;

# fetch the news
$WGET -r -np -x -nH -k -E -l1 -p "http://mobile.nytimes.com/";

# fix the encoding declaration
find $TEMP_DIR -name "*.html" -exec sed -i "" -e "s/166px/600px/" "{}" \;

# get rid of robots.txt and favicon.ico
rm favicon.ico; rm robots.txt;

UTCNOW=`date -u "+%Y-%m-%dT%H:%I:%SZ"`

cat > manifest.xml <<EOF
<?xml version="1.0" encoding="utf-8"?>
<package>
  <metadata>
    <dc-metadata>
      <Title>The New York Times (mobile edition)</Title>
      <Description>Last updated: $UTCNOW</Description>
      <Date>$UTCNOW</Date>
      <Format>html</Format>
      <Language>eng</Language>
      <Type>book</Type>
    </dc-metadata>
    <y-metadata>
      <FileSize>000</FileSize>
      <ItemSize>000</ItemSize>
      <startpage>index.html</startpage>
      <version>000</version>
    </y-metadata>
  </metadata>
</package>
EOF

# notify start of copy
$GROWLNOTIFY -m "Copying The New York Times (mobile edition) to the iLiad";

# clean the current iLiad data, move this stuff to the iLiad
rm -rf $ILIAD/newspapers/nytimes;
mkdir $ILIAD/newspapers/nytimes;
cp -R ./ /Volumes/iLiad/newspapers/nytimes/;

# remove the temp dir
rm -rf $TEMP_DIR;

# notify start of successful transfer
$GROWLNOTIFY -m "The New York Times (mobile edition) saved on the iLiad, enjoy!";
